package server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CustomerFile {

	// to write and read customer files

	File filename;
	FileWriter fw;
	FileReader reader;

	public CustomerFile(String name) {
		filename = new File(name+".txt");
		//System.out.println("File obj is ready for "+name);
	}

	public void updateFile(String itemID, int quantity) {
		try{
			// if file exists append
			if (filename.exists()) {
				fw = new FileWriter(filename, true);
				fw.write("\nItem: " + itemID + "\t" + "Quantity: "+ quantity + "\r");
				System.out.println("Added to the existing file.");
			} else {
				// else write
				fw = new FileWriter(filename);
				fw.write("Item: " + itemID + "\t" + "Quantity: "+ quantity + "\r");
				System.out.println("Created new file.");
			}
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	boolean readFile(String checkFor, int num){
		boolean result = false;
		try{
			if (filename.exists()){
				// read file
				System.out.println("file exists...");
				String boughtItem;
				String [] details = new String [4];

				reader = new FileReader(filename);
				BufferedReader line = new BufferedReader(reader);
				int totalBought = 0;
				
				while ((boughtItem = line.readLine())!=null){
					details = boughtItem.split("\\s");
					if(details[1].equals(checkFor)){
						totalBought +=  Integer.parseInt(details[3]);
					}
				}
				System.out.println("Client possesses: "+totalBought);
				if(totalBought>=num){ 
					result = true;
				}else{
					//false
				}
				line.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("Qualified for exchange: "+result);
		return result;
	}
}
